<?php

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;

class Fbpage extends Eloquent implements UserInterface, RemindableInterface {

	use UserTrait, RemindableTrait;
	const _LIMIT_PAGE_NOTI = 15;
	/**
	 * The database table used by the model.
	 *
	 * @var string
	 */
	protected $table = 'fbpages';

	public static function getPagesNotifications($pages) {
		$batch = '[';
		$batchPiece = '';
		$relativeGraph = str_replace('https://graph.facebook.com/', '', Config::get('app.fbapi'));
		foreach ($pages as $page) {
			$batchPiece[] = '{"relative_url":"' . $relativeGraph . $page['fb_page_id'] . '/notifications?fields=id,created_time,title,link,object,from,unread&limit='.self::_LIMIT_PAGE_NOTI.'&access_token=' . $page['page_token'] . '", "method":"GET"}';
		}
		$batch .= implode(',', $batchPiece);
		$batch .= ']';
		$params = array(
			'include_headers' => 'false',
			'batch' => $batch
		);
		$response = HomeController::curl(Config::get('app.fbapi') . '?access_token=' . Auth::user()->access_token, $params);
		return json_decode($response, true);
	}

	public static function fbRealTimeSubForPage($pages) {
		$batch = '[';
		$batchPiece = [];
		$relativeGraph = str_replace('https://graph.facebook.com/', '', Config::get('app.fbapi'));
		foreach ($pages as $page) {
			$batchPiece[] = '{"relative_url":"' . $relativeGraph . $page['fb_page_id'] . '/subscribed_apps?access_token=' . $page['page_token'] . '", "method":"POST"}';
		}
		$batch .= implode(',', $batchPiece);
		$batch .= ']';
		$params = array(
			'include_headers' => 'false',
			'batch' => $batch
		);
		$response = HomeController::curl(Config::get('app.fbapi') . '?access_token=' . Auth::user()->access_token, $params);
		return json_decode($response, true);
	}

	public static function generateUserChannel($uid) {
		return md5('HJss/4@#532.*3m' . $uid);
	}
	public static function pagePostApiUrl($pageId){
		$relativeGraph = str_replace('https://graph.facebook.com/', '', Config::get('app.fbapi'));
	    return $relativeGraph . $pageId . "/feed";
	}
	public static function pagePhotosApiUrl($pageId){
		$relativeGraph = str_replace('https://graph.facebook.com/', '', Config::get('app.fbapi'));
	    return $relativeGraph . $pageId . "/photos";
	}
	public static function createMassPagePost($params) {
		$pages = self::where('user_id', Auth::user()->id)->select('id', 'fb_page_id', 'page_name', 'page_token')->get();
		$arrPage = [];
		$arrBatch= [];
		$sdate = strtotime($params['pdate'] . ' ' . $params['ptime']);
		$published = intval(Input::get('published'));
		$dbParams = [];
		$apiUrl = null;
		// is schedule?
		if($sdate - time() > 600){
			$published = 0;
		}

		foreach ($pages as $page) {
			$arrPage[$page->fb_page_id] = array('page_name' => $page->page_name, 'page_token' => $page->page_token, 'page_id' => $page->id);
		}
		$i = 1;
		foreach($params['messages'] as $idx => $message){
			$apiUrl = self::pagePostApiUrl($params['page_id']);
			if(!isset($params['links'][$idx])) 		$params['links'][$idx] = '';
			if(!isset($params['pictures'][$idx])) 	$params['pictures'][$idx] = '';
			if(!isset($params['descs'][$idx])) 		$params['descs'][$idx] = '';
			if(!isset($params['captions'][$idx])) 	$params['captions'][$idx] = '';
			if(!isset($params['names'][$idx])) 		$params['names'][$idx] = '';

			if(!array_key_exists($params['page_id'], $arrPage)){
				array_push($arrBatch, null);
				continue;
			}
			$body = array(
				'access_token' => $arrPage[$params['page_id']]['page_token'],
				'message' => $message,
				'link' => $params['links'][$idx],
				'name' => $params['names'][$idx],
				'caption' => $params['captions'][$idx],
				'description' => $params['descs'][$idx],
				'published' => $published,
				'picture' => $params['pictures'][$idx]
			);
			// schedule?
			if($sdate - time() > 600){
				$body['scheduled_publish_time'] = $sdate;
			}
			array_push($arrBatch, array(
				"method" => "POST",
				"relative_url" => $apiUrl,
				"body" => http_build_query($body)
			));
			array_push($dbParams, array(
					'post_name' => $params['names'][$idx],
					'post_url' => $params['links'][$idx],
					'post_message' => $message,
					'post_picture' => $params['pictures'][$idx],
					'post_caption' => $params['captions'][$idx],
					'post_desc' => $params['descs'][$idx],
					'fb_post_id' => '',
					'rawdata' => '',
					'photo' => '',
					'page_id' => $params['page_id'],
					'post_publish_time' => date('Y/m/d H:i:s'),
					'post_type' => 'STATUS',
					'user_id' => Auth::user()->id
				)
			);

			$i++;
		}
		// sending batcvh request to FB
		$responseId = [];
		try{
			$api = Config::get('app.fbapi') . '?access_token=' . Auth::user()->access_token;
			$response = json_decode(HomeController::curl($api, array('batch' => json_encode($arrBatch), 'include_headers' => 'false')), true);
			if(is_array($response) && !empty($response)){
				$i = 0;
				foreach($response as $res){
					if($res['code'] == 200 && isset($res['body'])){
						$body = json_decode($res['body'], true);
						if(isset($body['id'])) {
							array_push($responseId, $body['id']);
							// save to DB
							$dbParams[$i]['fb_post_id'] = $body['id'];
						}
						else {
							array_push($responseId, $res['body']);
						}
					}
					else{
						$dbParams[$i]['rawdata'] = json_encode($res);
						if(isset($res['body'])){
							array_push($responseId, json_decode($res['body'], true));
						}
						elseif(isset($res['message'])){
							array_push($responseId, array('error' => $res));
						}
						else{
							array_push($responseId, null);
						}
					}
					$i++;
				}
				Pagepost::insert($dbParams);
			}
		}
		catch(Exception $e){
			echo $e->getMessage();
			exit(0);
		}
		return $responseId;
	}
	public static function createPagePost($params) {
		$pages = self::where('user_id', Auth::user()->id)->select('id', 'fb_page_id', 'page_name', 'page_token')->get();
		$arrPage = [];
		$arrBatch= [];
		$sdate = strtotime($params['pdate'] . ' ' . $params['ptime']);
		$published = intval(Input::get('published'));
		$dbParams = [];
		// is schedule?
		if($sdate - time() > 600){
			$published = 0;
		}

		foreach ($pages as $page) {
			$arrPage[$page->fb_page_id] = array('page_name' => $page->page_name, 'page_token' => $page->page_token, 'page_id' => $page->id);
		}
		foreach($params['pages'] as $fbPageId){
			if(!array_key_exists($fbPageId, $arrPage)){
				array_push($arrBatch, null);
				continue;
			}
			if(!empty($params['photo'])) {
				$apiUrl = self::pagePhotosApiUrl($fbPageId);
			}
			else {
				$apiUrl = self::pagePostApiUrl($fbPageId);
			}

			try{
				if(!empty($params['photo'])) {
					// $body['url'] = URL::to($params['photo']);
					$body = array(
						'access_token' => $arrPage[$fbPageId]['page_token'],
						// 'url' => 'http://s1.haiivl.com/data/600_65d19cec-0f5f-48dc-998a-5ab7acf56e5b.jpg',
						'url' => URL::to($params['photo']),
						'message' => $params['message'],
						'published' => $published
					);
				}
				else {
					$body = array(
						'access_token' => $arrPage[$fbPageId]['page_token'],
						'message' => $params['message'],
						'link' => $params['link'],
						'name' => $params['name'],
						'caption' => $params['caption'],
						'description' => $params['desc'],
						'published' => $published,
						'picture' => $params['picture']
					);
				}
				// schedule?
				if(!$published){
					$body['scheduled_publish_time'] = $sdate;
				}
				array_push($arrBatch, array(
					"method" => "POST",
					"relative_url" => $apiUrl,
					"body" => http_build_query($body)
				));
				array_push($dbParams, array(
						'post_name' => $params['name'],
						'post_url' => $params['link'],
						'post_message' => $params['message'],
						'post_picture' => $params['picture'],
						'post_caption' => $params['caption'],
						'post_desc' => $params['desc'],
						'fb_post_id' => '',
						'rawdata' => '',
						'photo' => $params['photo'],
						'page_id' => $arrPage[$fbPageId]['page_id'],
						'post_publish_time' => date('Y/m/d H:i:s'),
						'post_type' => 'STATUS',
						'user_id' => Auth::user()->id
					)
				);
			}
			catch(Exception $e){
				echo $e->getMessage();
				exit(0);
			}
		}
		// sending batcvh request to FB
		$responseId = [];
		try{
			$api = Config::get('app.fbapi') . '?access_token=' . Auth::user()->access_token;
			$response = json_decode(HomeController::curl($api, array('batch' => json_encode($arrBatch), 'include_headers' => 'false')), true);
			if(is_array($response) && !empty($response)){
				$i = 0;
				foreach($response as $res){
					if($res['code'] == 200 && isset($res['body'])){
						$body = json_decode($res['body'], true);
						if(isset($body['id'])) {
							array_push($responseId, $body['id']);
							// save to DB
							$dbParams[$i]['fb_post_id'] = $body['id'];
						}
						else {
							array_push($responseId, $res['body']);
						}
					}
					else{
						$dbParams[$i]['rawdata'] = json_encode($res);
						if(isset($res['body'])){
							array_push($responseId, json_decode($res['body'], true));
						}
						elseif(isset($res['message'])){
							array_push($responseId, array('error' => $res));
						}
						else{
							array_push($responseId, null);
						}
					}
					$i++;
				}
				Pagepost::insert($dbParams);
			}
		}
		catch(Exception $e){
			echo $e->getMessage();
			exit(0);
		}

		return $responseId;
	}
	public static function getSingnedRequest($singedParam) {
		$data_signed_request = explode('.',$singedParam); // Get the part of the signed_request we need.
		$jsonData = base64_decode($data_signed_request['1']); // Base64 Decode signed_request making it JSON.
		$objData = json_decode($jsonData,true); // Split the JSON into arrays.
		/*$pageData = $objData['page'];
		$liked = $pageData['liked']; //you have the liked boolean
		$sourceData = $objData['app_data']; // yay you got the damn data in an string, slow clap for you
		$appDataArray = explode(';',$sourceData); // explode the app data because you hate it as a string, only do this if you are sending an array of variables through*/ 

		return $objData;
	}
}
